﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Shop.Model;
using System.Web;
using Shop.Framework.Keys;
using System.Web.Caching;
using System.Web.Script.Serialization;

namespace Shop.Framework.Services {
    public class DesignerService : BaseService {
        public List<Designer> GetDesigners() {
            try {
                
                List<Designer> designer = HttpRuntime.Cache.Get(CacheKey.DesignerList) as List<Designer>;
                if (designer == null) {
                    designer = Context.Designers.ToList();
                    HttpRuntime.Cache.Add(CacheKey.DesignerList,
                    designer,
                    null,
                    DateTime.Now.AddHours(2),
                    Cache.NoSlidingExpiration,
                    CacheItemPriority.Normal,
                    null);
                }

                return designer;
            } catch (Exception ex) {
                throw new Exception("An error is encountered while fetching the designer list", ex);
            }
        }

        internal string GetDesignerJson() {
            Random rand = new Random();
            List<Designer> catList = GetDesigners();

            List<TagTemplate> tList = new List<TagTemplate>();
            foreach (var t in catList) {

                tList.Add(new TagTemplate {
                    tag = t.Name,
                    freq = RandomNumber(rand).ToString(),
                    link = string.Format("designer/products/{0}/{1}.html", t.Name.Trim(), t.IdDesigner)
                });
            }

            JavaScriptSerializer ser = new JavaScriptSerializer();
            return ser.Serialize(tList);
        }

        private int RandomNumber(Random rand) {
            return rand.Next(1, 20);
        }

        private class TagTemplate {
            public string tag { get; set; }
            public string freq { get; set; }
            public string link { get; set; }
        }
    }
}
